# -*- coding: utf-8 -*-
#
# Copyright 2008 Yejun Yang
#
import posixpath

import mako.lookup
import mako.template

class MakoLookup(mako.lookup.TemplateLookup):
    def __init__(self, directory, module_directory=None, **kwargs):
        self.directory = posixpath.normpath(directory)
        if module_directory is None:
            self.module_directory = self.directory
        else:
            self.module_directory = posixpath.normpath(module_directory)
        self.__collection = {}
        self._uri_cache = {}
        self.__kwargs = kwargs
        
    def get_template(self, uri):
        uri = uri.strip('/')
        try:
            return self.__collection[uri]
        except KeyError:
            return self.__load(uri)
            
    def __load(self, uri):
        package = self.module_directory.replace('/','.')
        module_name = package+'.'+uri.replace('.','_').replace('/','.')
        self.__collection[uri] = mako.template.ModuleTemplate(module = __import__(module_name, fromlist=[package]), lookup = self, **self.__kwargs)
        return self.__collection[uri]
        
    def put_string(self, uri, text):
        self.__collection[uri] = mako.template.Template(text, lookup=self, uri=uri, **self.__kwargs)
        
    def put_template(self, uri, template):
        self.__collection[uri] = template
        
        
        